package com.cjh.utils;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 消费监视
 */
@Component
public class WatchMessageImpl implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 消息到达交换机的回调
     *
     * @param correlationData
     * @param ack             是否到达交换机
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("消息正常到达交换机");
        } else {
            System.out.println("消息没有到达交换机原因：" + cause);
        }
    }

    /**
     * 消息由交换机到达队列失败之后的回调
     *
     * @param message    消息体
     * @param replyCode  回调的状态码
     * @param replyText  文本
     * @param exchange   交换机的名称
     * @param routingKey 路由名
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String
            routingKey) {
        System.out.println(new String(message.getBody()) + "到达队列失败" + replyCode + " " + replyText + " 交换机为:" + exchange + " 路由 key:" + routingKey);
        //处理重新发送的问题
    }
}